<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button type="primary" plain @click="handleSubmit('保存')"
              >保存</el-button
            >
            <!-- <el-button type="primary" @click="handleSubmit('提交')"
              >提交</el-button
            > -->
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container knowledge-form">
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据来源" prop="source">
              <el-select
                class="w-full"
                v-model="formData.source"
                placeholder="请选择数据来源"
              >
                <el-option
                  v-for="item in knowledge_source"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务类型" prop="businessType">
              <el-select
                class="w-full"
                v-model="formData.businessType"
                placeholder="请选择业务类型"
              >
                <el-option
                  v-for="item in knowledge_business_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属分类" prop="type">
              <el-select
                class="w-full"
                v-model="formData.type"
                placeholder="请选择所属分类"
              >
                <el-option
                  v-for="item in knowledge_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="问题描述" prop="content">
              <!-- <el-input v-model="formData.summary" /> -->
              <editor
                class="w-full"
                v-model="formData.content"
                :min-height="192"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="处理方案" prop="solution">
              <el-input
                type="textarea"
                rows="8"
                v-model="formData.solution"
                placeholder="请输入处理方案"
              />
              <!-- <editor
                class="w-full"
                v-model="formData.solution"
                :min-height="192"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属模块" prop="module">
              <el-select
                class="w-full"
                v-model="formData.module"
                filterable
                placeholder="请选择所属模块"
              >
                <el-option
                  v-for="item in knowledge_module"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="上传附件" prop="fileList">
              <!-- 
                v-model:file-list="formData.fileList" -->
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="
                  rawFile => beforeAvatarUpload(rawFile, 'type02')
                "
                :http-request="params => requestFile(params, 'type02')"
                :accept="uploadType['type02'].toString()"
                :limit="10"
                :show-file-list="false"
              >
                <el-button type="default" style="font-size: 14px"
                  ><el-icon><UploadFilled /></el-icon>上传附件</el-button
                >
                <template #tip>
                  <div class="el-upload__tip float-right">
                    支持格式{{ uploadType['type02'].toString() }}
                    ，单个文件不能超过200MB
                  </div>
                </template>
              </el-upload>
              <div class="text-14px mt-10px" style="width: 100%">
                <div
                  v-for="(item, index) in formData.fileList"
                  :key="item.fileName"
                >
                  <el-link :href="item.url" :underline="false" type="primary">{{
                    item.origFileName
                  }}</el-link>
                  <el-button text plain @click="delFileName(index)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="来电号码" prop="phone">
              <!-- <el-input v-model="formData.summary" /> -->
              <el-input v-model="formData.phone" placeholder="请输入来电号码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="问题发生地" prop="site">
              <el-select
                class="w-full"
                v-model="formData.site"
                placeholder="请选择问题发生地"
              >
                <el-option
                  v-for="item in problem_site"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    />
  </div>
</template>
<script setup name="KnowledgeForm">
import { useRouter, useRoute } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { setKnowledge, getKnowledgeDetail } from '@/api/officeManage/knowledge'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  skipToError,
  getTreeNodeByParam,
  getPricipalId,
  viewFile
} from '@/utils/commo'
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})

const {
  problem_site,
  knowledge_source,
  knowledge_business_type,
  knowledge_type,
  knowledge_module
} = proxy.useDict(
  'problem_site', //问题发生地
  'knowledge_source', //知识库来源
  'knowledge_business_type', //知识库业务类型
  'knowledge_type', //知识库所属分类
  'knowledge_module' //知识库中新增所属模块
)

const props = defineProps({
  knowledgeData: {
    type: Object,
    require: true,
    default: null
  }
})

const data = reactive({
  formData: { fileList: [] },
  formRules: {
    source: [
      {
        required: true,
        message: '请输入数据来源',
        trigger: ['blur', 'change']
      }
    ],
    businessType: [
      {
        required: true,
        message: '请输入业务类型',
        trigger: ['blur', 'change']
      }
    ],
    type: [
      {
        required: true,
        message: '请输入所属分类',
        trigger: ['blur', 'change']
      }
    ],
    content: [
      {
        required: true,
        message: '请输入问题描述',
        trigger: ['blur', 'change']
      }
    ],
    solution: [
      {
        required: true,
        message: '请输入处理方案',
        trigger: ['blur', 'change']
      }
    ],
    site: [
      {
        required: false,
        message: '请输入问题发生地',
        trigger: ['blur', 'change']
      }
    ]
  },
  dialogParam: {}
})
const { formData, formRules, dialogParam } = toRefs(data)

watch(
  () => route.query.knowledgeId,
  () => {
    if (route.query.knowledgeId && route.name == type.name) {
      getFormData(route.query.knowledgeId)
    }
  },
  {
    immediate: true
  }
)
// 初始化
function init() {}
/** 获取产品详情
 * @param {number}  id 表单id
 */
function getFormData(id) {
  return new Promise((resolve, reject) => {
    getKnowledgeDetail(id).then(async res => {
      let resData = {}
      resData = res.data
      formData.value = { ...formData.value, ...resData }
      resolve(res)
    })
  })
}
// 保存
function handleSubmit(e) {
  const formParam = { ...formData.value }
  proxy.$refs.form.validate((valid, done, msg) => {
    if (valid) {
      setKnowledge(formParam).then(res => {
        proxy.$modal.msgSuccess('保存成功!')
        handleReturn()
        getFormData(res.data.id)
      })
    }
  })
}

function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

const uploadType = {
  type01: ['.xls', '.xlsx'],
  type02: [
    '.rar',
    '.zip',
    '.doc',
    '.docx',
    '.pdf',
    '.xls',
    '.xlsx',
    '.ppt',
    '.pptx',
    '.gif',
    '.jpg',
    '.jpeg',
    '.png'
  ]
}
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile, type) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = uploadType[type].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      `上传文件只能是${uploadType[type]
        .toString()
        .replace(/\./g, '')
        .replace(/,/g, '、')}格式!`
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params, type) {
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('bucketName', 'article')
  uploadFile(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
      console.log('formData.value==>', formData.value)
      formData.value.fileList.push(res.data)
    }
  })
}
// 删除附件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      // let fule = {
      //   // bucketName: 'article',
      //   fileName: formData.value.fileList[index].fileName
      // }
      const res = await delFile(formData.value.fileList[index].fileName)
      if (res.code === 200) {
        formData.value.fileList.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
// 预览文件
function viewFiles(url) {
  viewFile(url, useUserStore().userInfo.nickName)
}

init()
</script>
<style scoped></style>
